<?php
/**
 * Created by PhpStorm.
 * User: xiaomage
 * Date: 2020/12/22
 * Time: 8:50
 */

namespace app\system\controller;


use app\system\logic\User;
use common\ApiReturn;
use component\system\system_message\SystemMessage;
use component\system\system_role\SystemRole;
use component\system\system_user\SystemUser;
use component\system\system_user\SystemUserValidate;
use component\system\system_user_auth\SystemUserAuth;
use component\system\system_user_login\SystemUserLogin;

class UserCenter extends System
{
    /**
     * 获取个人信息
     * @return \think\Response
     */
    public function info()
    {
        return ApiReturn::success(SystemUser::instance()->find(User::uuid()));
    }

    /**
     * 设置个人信息
     * @return \think\Response
     */
    public function setInfo()
    {
        $data = request()->only(['nickname', 'phone', 'email', 'avatar']);
        $data['id'] = User::uuid();
        return ApiReturn::auto(SystemUser::instance()->save($data));
    }

    /**
     * 设置密码
     * @return \think\Response
     */
    public function setPassword()
    {
        $data = request()->only(['origin', 'password', 'confirm']);

        if (empty($data['origin'])) {
            return ApiReturn::validate('请输入原始密码');
        }

        $record = SystemUser::instance()->login(User::get('username'), $data['origin']);
        if (empty($record)) {
            return ApiReturn::validate('原始密码错误');
        }

        $data['id'] = User::uuid();
        unset($data['origin']);

        return ApiReturn::auto(SystemUser::instance()->setValidate(SystemUserValidate::class)->save($data, 'setPassword'));
    }

    /**
     * 更新缓存
     * @return \think\Response
     */
    public function clearCache()
    {
        // 重置用户权限
        User::setAuth();

        return ApiReturn::success();
    }

    /**
     * 获取登入历史
     * @return \think\Response
     */
    public function history()
    {
        return ApiReturn::success(SystemUserLogin::instance()->getListByUserId(User::uuid()));
    }

    /**
     * 获取消息通知
     * @return \think\Response
     */
    public function message()
    {
        $read_time = request()->param('read_time', null);

        return ApiReturn::success(SystemMessage::instance()->getListByUserId(User::uuid(), $read_time));
    }

    public function getAuth()
    {
        $user_auth = SystemUserAuth::instance()->getByUserId(User::uuid());

        $role_auth = SystemRole::instance()->find(['id' => $user_auth->role_id]);

        $result = [];
        if ($user_auth['menu']) {
            $result = array_merge($user_auth['menu'], $result);
        }

        if ($role_auth['menu']) {
            $result = array_merge($role_auth['menu'], $result);
        }

        $result=array_values(array_unique($result));

        return ApiReturn::success($result);
    }
}